﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Enterprise.Infrastructure
{
    /// <summary>
    /// @各种扩展类 主要为EasyUI提供Json数据
    /// </summary>
    public static class Extension
    {
        #region "DataTable扩展方法 主要为EasyUI提供Json"
        /// <summary>
        /// 将数据表转换成Json
        /// </summary>
        /// <param name="dt">System.Data.DataTable</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>Json</returns>
        public static string ToJsonForEasyUiGrid(this DataTable dt, int page, int pageSize)
        {
            return ExcuteResultToJson(dt, page, pageSize);    
        }

        /// <summary>
        /// 将数据表转换成Json
        /// </summary>
        /// <param name="dt">System.Data.DataTable</param>
        /// <returns>Json</returns>
        public static string ToJsonForEasyUiList(this DataTable dt)
        {
            return ExcuteResultToJson(dt);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">System.Data.DataTable</param>
        /// <param name="idField">Id字段</param>
        /// <param name="textField">Text字段</param>
        /// <param name="parentIdField">父Id字段</param>
        /// <param name="rootIdValue">根节点的ParentId</param>
        /// <param name="selecedId">默认选择Id</param>
        /// <returns></returns>
        public static string ToJsonForEasyuiComboTree(this DataTable dt, string idField, string textField, string parentIdField, string rootIdValue, string selecedId)
        {
            return ExcuteResultToComboTreeJson(dt, idField, textField, parentIdField, rootIdValue,selecedId);
        }

        #endregion

        #region "将Datatable输出为html表格 注意大数据请不要使用该方法 尽量使用分页datatable调用"
        public static string ToHtmlTable(this DataTable dt)
        {
            string html = "<table class=\"htmlgrid\">";
            html += "<tr>";
            foreach (DataColumn dc in dt.Columns)
            {                
                html += "<th>"+dc.ColumnName+"</th>";                
            }
            html += "</tr>";
            
            foreach (DataRow dr in dt.Rows)
            {
                html += "<tr>";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    html += "<td>" + dr[i] + "</td>";
                }
                html += "</tr>";
            }
            
            html += "</table>";
            return html;
        }
        #endregion

        #region "字符串扩展类"
        /// <summary>
        /// 获取字符串的真实长度：1个汉字为2
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static int RealLength(this string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        /// <summary>
        /// 截取字符串 用...代替
        /// </summary>
        /// <param name="strInput"></param>
        /// <param name="intLen"></param>
        /// <returns></returns>
        public static string CutString(this string strInput, int? intLen)
        {            
            if (intLen == null||intLen==0)
                return strInput;
            strInput = strInput.Trim();
            byte[] myByte = System.Text.Encoding.Default.GetBytes(strInput);
            if (myByte.Length > intLen)
            {
                string resultStr = "";
                for (int i = 0; i < strInput.Length; i++)
                {
                    byte[] tempByte = System.Text.Encoding.Default.GetBytes(resultStr);
                    if (tempByte.Length < intLen)
                    {

                        resultStr += strInput.Substring(i, 1);
                    }
                    else
                    {
                        break;
                    }
                }
                return resultStr + "...";
            }
            else
            {
                return strInput;
            }
        }

        /// <summary>
        /// 将字符串按指定的格式分割 返回(1,2,3,4) 方便查询
        /// </summary>
        /// <param name="str"></param>
        /// <param name="split"></param>
        /// <returns></returns>
        public static string IdsToInId(this string str,char split)
        {
            string strWhere = "";
            //获取该栏目所有的文章的数量用于分页程序  
            if (!str.Equals(""))
            {
                string[] ids = str.Split(split);
                foreach (string id in ids)
                {
                    strWhere += id + ",";
                }
                if (strWhere.Length > 0)
                {
                    strWhere = " (" + strWhere.Remove(strWhere.Length - 1) + ")";
                }
            }
            return strWhere;
        }

        /// <summary>
        /// 将object转换为Int32,如果转换失败返回null
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int? ToInt(this object str)
        {
            int r=0;
            if (!Object.Equals(str, null))
            {
                if (int.TryParse(str.ToString(), out r))
                {
                    return r;
                }
                else
                    return null;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 将object转换为Int32,如果转换失败返回null
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static decimal? ToDecimal(this object str)
        {
            decimal r = 0;
            if (!Object.Equals(str, null))
            {
                if (decimal.TryParse(str.ToString(), out r))
                {
                    return r;
                }
                else
                    return null;
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region "私有方法"
        /// <summary>
        /// 将Datable中指定页码的数据转换为Json格式
        /// </summary>
        /// <param name="dt">System.Data.Datatable</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        private static string ExcuteResultToJson(DataTable dt, int page, int pageSize)
        {            
            string JsonData="";
            int rowbegin = (page - 1) * pageSize;
            int rowend = page * pageSize;
            if (rowend > dt.Rows.Count)
                rowend = dt.Rows.Count;
            if (rowbegin <= dt.Rows.Count)
            {
                JsonData = "{\"total\":" + dt.Rows.Count + ",\"rows\":[";
                for (int i = rowbegin; i <= rowend - 1; i++)
                {
                    JsonData += "{";
                    foreach (DataColumn dc in dt.Columns)
                    {
                        string content = Microsoft.JScript.GlobalObject.escape(dt.Rows[i][dc.ColumnName].ToString());
                        JsonData += "\"" + dc.ColumnName + "\":\"" + content + "\",";
                    }
                    JsonData = JsonData.Remove(JsonData.Length - 1);
                    JsonData += "},";

                }
                JsonData = JsonData.Remove(JsonData.Length - 1);
                JsonData += "]}";
            }
            return JsonData;
        }

        /// <summary>
        /// 将DataTable转换为Json格式
        /// </summary>
        /// <param name="dt">System.Data.DataTable</param>
        /// <returns></returns>
        private static string ExcuteResultToJson(DataTable dt)
        {
            string JsonData = "";
            JsonData = "[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonData += "{";
                foreach (DataColumn dc in dt.Columns)
                {
                    string content = Microsoft.JScript.GlobalObject.escape(dt.Rows[i][dc.ColumnName].ToString());
                    JsonData += "\"" + dc.ColumnName + "\":\"" + content + "\",";
                }
                JsonData = JsonData.Remove(JsonData.Length - 1);
                JsonData += "},";
            }
            JsonData = JsonData.Remove(JsonData.Length - 1);
            JsonData += "]";
            return JsonData;
        }

        /// <summary>
        /// 将DataTable转换为Json格式
        /// </summary>
        /// <param name="dt">System.Data.DataTable</param>
        /// <param name="idField">Value字段</param>
        /// <param name="textField">text字段</param>
        /// <param name="parentIdField">父Id字段</param>
        /// <param name="rootIdValue"></param>
        /// <param name="selectedId">选择Id</param>
        /// <returns></returns>
        private static string ExcuteResultToComboTreeJson(DataTable dt, string idField, string textField, string parentIdField, string rootIdValue,string selectedId)
        {
            string[] selected_ids = selectedId.Split(',');
            string JsonData = "[";
            DataRow[] drs = dt.Select(parentIdField + "='" + rootIdValue+"'");
            foreach (var d in drs)
            {
                DataRow[] childdrs = dt.Select(parentIdField + "='" + d[idField]+"'");
                JsonData += "{";
                JsonData += "\"id\":\"" + d[idField] + "\",";
                if (selected_ids.Contains(d[idField].ToString()))
                    JsonData += "\"checked\":true,";
                JsonData += "\"text\":" + "\"" + d[textField] + "\"";
                if (childdrs.Count() > 0)
                {
                    JsonData += ",\"children\":";
                    JsonData += ExcuteResultToComboTreeJson(dt, idField, textField, parentIdField, d[idField].ToString(),selectedId);
                    JsonData += "},";
                }
                else
                {
                    JsonData += "},";
                }
            }
            JsonData = JsonData.Remove(JsonData.Length - 1);
            JsonData += "]";
            return JsonData;
        }

        #endregion

        #region 将领导签字转换成图片

        /// <summary>
        /// 电子签名
        /// </summary>
        /// <param name="username">rtx登录名</param>
        /// <param name="top">签名位置距离页面顶端</param>
        /// <param name="left">距离页面左边</param>
        /// <param name="width">图片宽度，高度按比例自动缩放</param>
        /// <returns></returns>
        public static string QianMing(this string username,int top,int left,int width)
        {
            //签名图片路径
            string imgurl="\\Styles\\images\\qianming\\"+username+".gif";
            return "<div style='position:relative;top:" + top + "px;left:" + left + "px'><img src='" + imgurl + "' alt='' border=0 width=" + width + "/></div>";
        }

        #endregion

    }

}
